package com.example.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.dto.UserAddEvaluationRecordDTO;
import com.example.entity.dto.UserGetParticipationRecordsDTO;
import com.example.entity.po.AuditRecord;
import com.example.entity.po.PrizeRule;
import com.example.entity.po.Shop;
import com.example.entity.vo.UserAuditRecordVO;
import com.example.exception.ServiceException;
import com.example.mapper.AuditRecordMapper;
import com.example.mapper.PrizeRuleMapper;
import com.example.mapper.ShopMapper;
import com.example.service.AuditRecordService;
import com.example.utils.CommonUtil;
import com.example.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zeran2023
 * @description 针对表【t_audit_record】的数据库操作Service实现
 * @createDate 2024-12-24 15:29:00
 */
@Service
@Slf4j
public class AuditRecordServiceImpl extends ServiceImpl<AuditRecordMapper, AuditRecord>
		implements AuditRecordService {
	@Autowired
	private AuditRecordMapper auditRecordMapper;

	@Autowired
	private ShopMapper shopMapper;

	@Autowired
	private PrizeRuleMapper prizeRuleMapper;

	@Autowired
	private CommonUtil commonUtil;

	@Override
	public List<UserAuditRecordVO> getParticipationRecords(UserGetParticipationRecordsDTO userGetParticipationRecordsDTO) {
		LambdaQueryWrapper<AuditRecord> queryWrapper = new LambdaQueryWrapper<>();

		// 条件(用户id)
		queryWrapper.eq(AuditRecord::getUserId, userGetParticipationRecordsDTO.getUserId());
		if (userGetParticipationRecordsDTO.getStatusId() != 0) { // 如果 statusId 不为 0，则查询对应状态
			queryWrapper.eq(AuditRecord::getStatusId, userGetParticipationRecordsDTO.getStatusId());
		}
		// 根据 dateFilter 过滤 createTime
		LocalDateTime now = LocalDateTime.now();
		String dateFilter = userGetParticipationRecordsDTO.getDate();

		// 根据日期过滤条件计算开始时间和结束时间
		LocalDateTime startTime = null;
		LocalDateTime endTime = null;

		switch (dateFilter) {
			case "today" -> {
				startTime = LocalDateTimeUtil.beginOfDay(now); // 今天凌晨
				endTime = now; // 当前时间
			}
			case "yesterday" -> {
				startTime = LocalDateTimeUtil.beginOfDay(now.minusDays(1)); // 昨天凌晨
				endTime = LocalDateTimeUtil.endOfDay(now.minusDays(1)); // 昨天 23:59:59
			}
			case "last30day" -> {
				startTime = now.minusDays(30); // 30 天前
				endTime = now; // 当前时间
			}
			case "all" -> {
				// 不限制开始时间
				// 不限制结束时间
			}
			default -> throw new ServiceException("无效的时间过滤条件：" + dateFilter);
		}

		// 设置查询条件
		if (startTime != null) {
			if (endTime != null) {
				// 如果有结束时间，使用 between
				queryWrapper.between(AuditRecord::getCreateTime, startTime, endTime);
			} else {
				// 如果没有结束时间，只限制开始时间
				queryWrapper.ge(AuditRecord::getCreateTime, startTime);
			}
		}

		// 排除已删除的记录
		queryWrapper.eq(AuditRecord::getDelFlag, 0);

		// 查询数据
		List<AuditRecord> auditRecords = auditRecordMapper.selectList(queryWrapper);

		List<Integer> shopIds = auditRecords.stream().map(AuditRecord::getShopId).toList();
		if (shopIds.isEmpty()) {
			// 如果 shopIds 为空，直接返回空结果，避免发送无效的 SQL 查询
			return Collections.emptyList();
		}
		// 根据shop表查询店铺名称
		List<Shop> shops = shopMapper.selectBatchIds(shopIds);

		// 将 shops 转换为 Map，key 为 shopId，value 为 Shop 对象
		Map<Long, String> shopMap = shops.stream().collect(Collectors.toMap(Shop::getShopId, Shop::getShopName));

		// 遍历 auditRecords，整合数据到 UserAuditRecordVO
		List<UserAuditRecordVO> platformRecords = auditRecords.stream().map(record -> {
			// 创建 UserAuditRecordVO 对象
			UserAuditRecordVO vo = new UserAuditRecordVO();
			// vo.setUserId(userGetParticipationRecordsDTO.getUserId());
			vo.setSubmitPlatform(record.getPlatformName());
			vo.setAuditStatus(record.getStatusId());
			vo.setOrderNumber(record.getOrderNumber());
			vo.setUploadImages(Arrays.stream(record.getCommentPhoto().split(",")).map(String::trim).collect(Collectors.toList()));
			vo.setRedPacketAmount(record.getAuditMoney());
			vo.setSubmitTime(CommonUtil.convertLocalDateTimeToTimestamp(record.getCreateTime()));
			vo.setAuditTime(CommonUtil.convertLocalDateTimeToTimestamp(record.getAuditTime()));

			// 根据 shopId 获取店铺名称
			vo.setShopName(shopMap.get(record.getShopId()));
			return vo;
		}).collect(Collectors.toList());

		// 处理平台信息，每条记录对应一个平台
		return platformRecords;
	}

	@Override
	public void addEvaluationRecordsSubmittedByUser(UserAddEvaluationRecordDTO userAddEvaluationRecordDTO,
													String token) {
		// 检查每一项是否为空或者null
		if (userAddEvaluationRecordDTO == null ||
				userAddEvaluationRecordDTO.getOrderNumber() == null ||
				userAddEvaluationRecordDTO.getSubmitPlatform() == null ||
				userAddEvaluationRecordDTO.getImagesWithBase64().isEmpty()) {
			throw new ServiceException("请填写完整信息");
		}
		// 处理手机号格式
		if (userAddEvaluationRecordDTO.getPhone().length() != 11) {
			throw new ServiceException("请输入11位正确的手机号");
		}
		LocalDateTime now = LocalDateTime.now();
		String userId = JwtUtil.parseTokenId(token);

		// 创建审核记录
		AuditRecord auditRecord = AuditRecord.builder()
				.userId(Long.valueOf(userId))
				.platformName(userAddEvaluationRecordDTO.getSubmitPlatform())
				.shopId(Integer.valueOf(userAddEvaluationRecordDTO.getShopId()))
				.orderNumber(userAddEvaluationRecordDTO.getOrderNumber())
				.phoneTail(userAddEvaluationRecordDTO.getPhone().substring(7))
				.statusId(1) // 1 表示待审核
				.createTime(now)
				.auditMoney(0.0)
				.build();

		// 获取商家配置信息
		PrizeRule prizeRule = prizeRuleMapper.selectById(userAddEvaluationRecordDTO.getShopId());
		Integer lastAuditTimeForHour = prizeRule.getLastAuditTime();
		auditRecord.setStopTime(now.plusHours(lastAuditTimeForHour));

		// 插入审核记录，获取主键 ID
		auditRecordMapper.insert(auditRecord);
		Integer auditRecordId = auditRecord.getAuditRecordId();

		// 处理 Base64 图片并上传
		List<String> selfImagePaths = userAddEvaluationRecordDTO.getImagesWithBase64().stream()
				.map(base64Image -> {
					String fileName = "record_image_" + UUID.randomUUID() + ".png"; // 使用 UUID 确保文件名唯一
					MultipartFile multipartFile = CommonUtil.convertBase64ToMultipartFile(base64Image, fileName);
					commonUtil.uploadFile(multipartFile, "record/" + auditRecordId);
					return fileName; // 返回上传的文件名
				})
				.collect(Collectors.toList());

		// 更新审核记录的图片路径字段
		auditRecord.setCommentPhoto(String.join(",", selfImagePaths));
		auditRecordMapper.updateById(auditRecord);
	}
}




